﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PMS.XCMG.Entity;
using System.Transactions;

namespace PMS.XCMG.Api
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class TransactionScopeAttribute : Attribute, IAsyncActionFilter
    {
        private IsolationLevel Level { get; set; }
        public TransactionScopeAttribute(IsolationLevel level = IsolationLevel.ReadCommitted)
        {
            this.Level = level;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            using (var trayScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                var nextContext = await next();
                if (nextContext.Exception == null)
                    trayScope.Complete();
            }
        }
    }
}
